<?php
/**
 * 购物车信息
 * Created by PhpStorm.
 * User: Jmashimaro
 * Date: 2015/1/25
 * Time: 17:26
 */
class CartApp extends MallbaseApp {

    private $user_id;
    private $version = '';
    private $method;
    private $common;
    /**
     * 初始化
     * CartApp constructor.
     * @author jyx
     * @date 2015/11/10
     */
    public function __construct() {
        $this->common = new CommonApp();
        $this->version = $_SERVER['HTTP_VERSION'];
        $this->method = strtoupper($_SERVER['REQUEST_METHOD']);
        if (!$this->user_id = $this->checkLogin()) {
            $this->ajax_return(ERROR_LOGIN, '请您登陆！');
        }
//        $this->version = 'HeShe/1.4';
//        $this->user_id = 101252;
    }

    /**
     * 购物车列表,1.3版本
     * @author jyx
     * @date 2015/10/12
     */
    public function index() {
        $action = '购物车列表';
        setLogParameter($action);
        $this->check_method('GET');
        $model = m('cart');
        if ($this->version == IOS_VERSION) {
            //获取购物车中的的商品信息
            $data = $this->_getCartInfo($this->user_id, $model);
            $this->ajax_return(FLAG_OK, '', $data);
        } else {
            $where_user_id = $this->user_id ? " AND cart.user_id=" . $this->user_id : '';
            $sql = 'SELECT cart.*,s.store_name,cart.rec_id FROM '.DB_PREFIX.'cart cart LEFT JOIN '.DB_PREFIX."store s
                ON cart.store_id = s.store_id WHERE cart.user_id={$this->user_id} ORDER BY cart.rec_id DESC";
            $cart_items = $model->getAll($sql);
            if ($cart_items) {
                foreach ($cart_items as $key=>$val) {
                    $val['goods_image'] = $this->common->isMySelfImage($val['goods_image'], GOODS_S_IMG);
                    $cart_items[$key] = $val;
                }
            }
            if (!$cart_items) {
                $this->ajax_return(FLAG_ERROR, '购物车里没有商品！');
            }
            $this->ajax_return(FLAG_OK, '', $cart_items);
        }
    }

    /**
     * 获取购物车中商品的信息
     * @param $user_id
     * @param $model:类的对像
     * @return array
     * @author jyx
     * @date 2015/11/03
     */
    private function _getCartInfo($user_id, $model) {
        $cart = array();
        $sql = "SELECT ct.rec_id,ct.goods_id,ct.goods_name,ct.spec_id,ct.specification,ct.quantity,ct.goods_image,
                ct.checked,s.store_id,s.store_name,s.store_logo,gs.price,gs.discount_spec_price,gs.is_show_discount,
                g.act_start_time,g.act_end_time FROM ".DB_PREFIX."cart ct LEFT JOIN ".DB_PREFIX."store s ON ct.store_id=s.store_id
                LEFT JOIN ".DB_PREFIX."goods_spec gs ON gs.spec_id=ct.spec_id LEFT JOIN ".DB_PREFIX."goods g ON ct.goods_id=g.goods_id
                WHERE ct.user_id={$user_id} ORDER BY ct.rec_id DESC";
        $tmp = $model->getAll($sql);
        if ($tmp) {
            $time = time();
            $cart['total_price'] = 0.00;
            foreach($tmp as $key=>$val) {
                //显示商品图片
                $val['goods_image'] = $this->common->isMySelfImage($val['goods_image'], GOODS_IMG);
                $val['store_logo'] = $val['store_logo'] ? QINIU_URL.$val['store_logo'] : '';
                $val['is_show_discount'] = ($val['is_show_discount'] == 2) ? 2 : 1;
                $val['checked'] = intval($val['checked']);
                $val['discount'] = $this->common->isAct($val, false);
                if ($val['checked'] == 1) {
                    $cart['total_quantity'] = intval($cart['total_quantity'] + $val['quantity']); //计算选择商品的总数量
                    $val['discount_price'] = $val['discount'] == 1 ? $val['discount_spec_price'] : $val['price'];
                    $cart['total_price'] = floatval($cart['total_price'] + ($val['quantity'] * $val['discount_price']));//商品总价
                }
                $cart['goods'][$val['store_id']][] = $val;
            }
            $cart ['goods'] = array_values($cart['goods']);
            $cart['total_price'] = sprintf("%.2f", $cart['total_price']);
            $cart['goods'] = array_merge(array(), $cart['goods']);
        }
        return $cart;
    }

    /**
     * 加入购物车
     * @author jiayanxiu
     * @date 2015/11/03
     */
    public function add() {
        $action = '加入购物车';
        setLogParameter($action);
        $this->check_method('POST');
        $spec_id = $this->get_gp('spec_id', 'P');//商品规信息格表的id
        if(!$spec_id){
            $this->ajax_return(FLAG_ERROR, '没有商品信息！');
        }
        $quantity = $this->get_gp('quantity', 'P');//购买商品的数量
        $model = m('cart');
        //如果是最新版本
        if ($this->version == IOS_VERSION) {
            //判断此商品是否存在
            $sql = "SELECT gs.spec_id,gs.goods_id,gs.price,gs.stock,gs.spec_1,gs.spec_2,g.goods_name,g.store_id,
                g.default_image,g.spec_name_1,g.spec_name_2 FROM ".DB_PREFIX."goods_spec gs LEFT JOIN ".DB_PREFIX."goods g
                ON gs.goods_id=g.goods_id WHERE gs.spec_id={$spec_id} AND g.if_examine = 1 AND g.if_finance = 1
                AND g.if_show = 1 AND g.closed = 0 LIMIT 1";
            $spec = $model->getRow($sql);
            if (!$spec) {
                $this->ajax_return(FLAG_ERROR, '商品不存在！');
            }
            if ($this->user_id == $spec['store_id']) {
                $this->ajax_return(FLAG_ERROR, '这是您自己的商品不能加入购物车！');
            }

            $specification = '';
            if ($spec['spec_name_1']) {
                $specification = $spec['spec_name_1'].':'.$spec['spec_1'].' ';
            }
            if ($spec['spec_name_2']) {
                $specification .= $spec['spec_name_2'].':'.$spec['spec_2'];
            }
            //判断此商品是否存在购物车中
            $sql = "SELECT rec_id,quantity FROM ".DB_PREFIX."cart WHERE user_id={$this->user_id} AND spec_id={$spec_id}";
            $cart = $model->getRow($sql);
            if (($quantity + $cart['quantity']) > $spec['stock']){
                $this->ajax_return(FLAG_ERROR, '商品库存数量不足！');
            }
            $model->begin();//开始事物
            if ($cart) {
                //如果存在，则进行更新
                $sql = "UPDATE ".DB_PREFIX."cart SET quantity=quantity+{$quantity} WHERE rec_id={$cart['rec_id']} AND user_id={$this->user_id}";
            } else {
                //不存在则添加
                $sql = "INSERT INTO ".DB_PREFIX."cart (user_id,store_id,spec_id,goods_id,goods_name,specification,price,quantity,goods_image)
                VALUES ({$this->user_id},{$spec['store_id']},{$spec['spec_id']},{$spec['goods_id']},'".addslashes($spec['goods_name'])."',
                '".addslashes($specification)."',{$spec['price']},{$quantity},'{$spec['default_image']}')";
            }
            $flag = $model->query($sql);
            if ($flag === false) {
                $model->roll_back();
                $this->ajax_return(FLAG_ERROR, '加入购物车失败！');
            }
            $sql = "SELECT goods_id FROM ".DB_PREFIX."goods_statistics WHERE goods_id={$spec['goods_id']}";
            if ($model->getRow($sql)) {//如果存在信息
                //更新被添加进购物车的次数
                $sql = "UPDATE ".DB_PREFIX."goods_statistics SET carts=carts+{$quantity} WHERE goods_id={$spec['goods_id']}";
                $res = $model->query($sql);
            } else {//不存在信息,则插入信息
                $sql = "INSERT INTO ".DB_PREFIX."goods_statistics (goods_id,carts) VALUES ({$spec['goods_id']},1)";
                $res = $model->query($sql);
            }
            if ($res === false) {
                $model->roll_back();
                $this->ajax_return(FLAG_ERROR, '更新购物车收藏次数失败！');
            }

            $model->commit();
            $this->ajax_return(FLAG_OK, '');
        } else {
            /* 是否有商品 */
            $spec_model = m('goodsspec');
            $spec_info  =  $spec_model->get(array(
                'fields'        => 'g.store_id,g.goods_id,g.goods_name,g.spec_name_1,g.spec_name_2,g.default_image,gs.spec_1,gs.spec_2,gs.stock,gs.price',
                'conditions'    => $spec_id,
                'join'          => 'belongs_to_goods',
            ));

            if (!$spec_info) {
                $this->ajax_return(FLAG_ERROR, '商品不存在！');
            }
            //如果是自己店铺的商品，则不能购买 *
            if ($spec_info['store_id'] == $this->user_id) {
                $this->ajax_return(FLAG_ERROR,'这是您自己的商品，不能进行购买！');
            }
            //是否添加过
            $item_info  = $model->get("spec_id={$spec_id} AND session_id='" . SESS_ID . "'");
            if (!empty($item_info)) {
                $this->ajax_return(FLAG_ERROR, '商品已经在购物车中！');
            }
            //商品是否已经卖完
            if ($quantity > $spec_info['stock']){
                $this->ajax_return(FLAG_ERROR, '商品数量不足！');
            }

            $spec_1 = $spec_info['spec_name_1'] ? $spec_info['spec_name_1'] . ':' . $spec_info['spec_1'] : $spec_info['spec_1'];
            $spec_2 = $spec_info['spec_name_2'] ? $spec_info['spec_name_2'] . ':' . $spec_info['spec_2'] : $spec_info['spec_2'];
            $specification = $spec_1 . ' ' . $spec_2;

            /* 将商品加入购物车 */
            $cart_item = array(
                'user_id'       => $this->checkLogin(),
                'session_id'    => SESS_ID,
                'store_id'      => $spec_info['store_id'],
                'spec_id'       => $spec_id,
                'goods_id'      => $spec_info['goods_id'],
                'goods_name'    => addslashes($spec_info['goods_name']),
                'specification' => addslashes(trim($specification)),
                'price'         => $spec_info['price'],
                'quantity'      => $quantity,
                'goods_image'   => addslashes($spec_info['default_image']),
            );

            /* 添加并返回购物车统计即可 */
            $model->add($cart_item);
            $cart_status = $this->get_cart_status();

            //更新被添加进购物车的次数
            $model_goodsstatistics = m('goodsstatistics');
            $model_goodsstatistics->edit($spec_info['goods_id'], 'carts=carts+1');

            //
            $this->ajax_return(FLAG_OK, '加入购物车成功！', $cart_status);

        }
    }


    /**
     * 更新购物车中的商品
     * @author jiayanxiu
     * @date 2015/11/03
     */
    public function update() {
        $action = '更新购物车中的商品';
        setLogParameter($action);
        if ($this->method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        $spec_id    = $this->get_gp('spec_id', 'P');//商品的扩展id
        $quantity   = $this->get_gp('quantity', 'P');//数量，可以正数可以负数
        $spec_id    = $spec_id ? intval($spec_id) : 0;
        $quantity   = $quantity ? intval($quantity): 0;
        if (!$spec_id || !$quantity){
            $this->ajax_return(FLAG_ERROR, '非法的参数！');
        }
        $model = m('cart');
        if ($this->version == IOS_VERSION) {
            //获取当前商品的信息
            $sql = "SELECT spec_id,goods_id,stock FROM ".DB_PREFIX."goods_spec WHERE spec_id={$spec_id}";
            $spec = $model->getRow($sql);
            if (!$spec) {
                $this->ajax_return(FLAG_ERROR, '没有此商品的规格！');
            }
            //获取购物车中商品的信息
            $sql = "SELECT rec_id,quantity FROM ".DB_PREFIX."cart WHERE user_id={$this->user_id} AND spec_id={$spec_id}";
            $cart = $model->getRow($sql);
            if (!$cart) {
                $this->ajax_return(FLAG_ERROR, '购物车中不存在此商品！');
            }
            if ($quantity+$cart['quantity'] < 1) {
                $this->ajax_return(FLAG_ERROR, '您最少必须购买一件商品！');
            }
            if (($quantity+$cart['quantity']) > $spec['stock']) {
                $this->ajax_return(FLAG_ERROR, '此规则的商品库存不足！');
            }
            $model->begin();
            //修改数量
            $sql = "UPDATE ".DB_PREFIX."cart SET quantity=quantity+{$quantity} WHERE rec_id={$cart['rec_id']}";
            $res = $model->query($sql);
            if ($res === false) {
                $model->roll_back();
                $this->ajax_return(FLAG_ERROR, '更新购物车中的商品数量失败！');
            }
            //更新收藏的购物车中商品的数量
            $sql = "UPDATE ".DB_PREFIX."goods_statistics SET carts=carts+{$quantity} WHERE goods_id={$spec['goods_id']}";
            $rs = $model->query($sql);
            if ($rs === false) {
                $model->roll_back();
                $this->ajax_return(FLAG_ERROR, '更新收藏购物车中的商品数量失败！');
            }
            $model->commit();
            //获取购物车中商品的信息
            $data = $this->_getCartInfo($this->user_id, $model);
            $this->ajax_return(FLAG_OK, '', $data);
        } else {
            //判断库存是否足够
            $model_spec = m('goodsspec');
            $spec_info  =  $model_spec->get($spec_id);
            if (!$spec_info) {
                $this->ajax_return(FLAG_ERROR, '没有此商品的规格！');
            }
            //数量有限
            if ($quantity > $spec_info['stock']) {
                $this->ajax_return(FLAG_ERROR, '没有充足的货源！');
            }
            /* 修改数量 */
            $where = "spec_id={$spec_id} AND session_id='" . SESS_ID . "'";
            /* 获取购物车中的信息，用于获取价格并计算小计 */
            $cart_spec_info = $model->get($where);
            /* 并没有添加该商品到购物车 */
            if (!$cart_spec_info) {
                $this->ajax_return(FLAG_ERROR, '并没有添加该商品到购物车！');
            }
            $store_id = $cart_spec_info['store_id'];
            /* 修改数量 */
            $model->edit($where, array(
                'quantity'  =>  $quantity,
            ));
            //返回JSON结果
            $cart_status = $this->get_cart_status();
            $cart_status['status']['subtotal']   =   $quantity * $cart_spec_info['price'];//小计
            $cart_status['status']['amount'] = $cart_status['carts'][$store_id]['amount'];//店铺购物车总计
            $this->ajax_return(FLAG_OK, '', $cart_status['status']);
        }
    }

    /**
     * 删除购物车中的商品
     * @author jiayanxiu
     * @date 2015/11/03
     */
    public function drop() {
        $action = '删除购物车中的商品';
        setLogParameter($action);
        if ($this->method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        $rec_id = $this->get_gp('rec_id', 'P');
        $model = m('cart');
        if ($this->version == IOS_VERSION) {
            //获取此商品的信息
            $sql = "SELECT goods_id,quantity FROM ".DB_PREFIX."cart WHERE rec_id={$rec_id} AND user_id={$this->user_id}";
            $cart = $model->getRow($sql);
            if (!$cart) {
                $this->ajax_return(FLAG_ERROR, '购物车没有该商品');
            }
            $model->begin();
            //从购物车中删除该商品
            $sql = "DELETE FROM ".DB_PREFIX."cart WHERE rec_id ={$rec_id} AND user_id={$this->user_id}";
            $res = $model->query($sql);
            if ($res === false) {
                $model->roll_back();
                $this->ajax_return(FLAG_ERROR, '删除商品失败！');
            }
            //更新购物车中此商品的收藏数量
            $sql = "SELECT carts FROM ".DB_PREFIX."goods_statistics WHERE goods_id={$cart['goods_id']}";
            $info = $model->getRow($sql);
            if ($info['carts'] < $cart['quantity']) {
                $sql = "UPDATE ".DB_PREFIX."goods_statistics SET carts=0 WHERE goods_id={$cart['goods_id']}";
            } else {
                $sql = "UPDATE ".DB_PREFIX."goods_statistics SET carts=carts-{$cart['quantity']} WHERE goods_id={$cart['goods_id']}";
            }
            $rs = $model->query($sql);
            if ($rs === false) {
                $model->roll_back();
                $this->ajax_return(FLAG_ERROR, '更新商品收藏次数失败！');
            }
            $model->commit();
            //获取购物车中商品的信息
            $data = $this->_getCartInfo($this->user_id, $model);
            $this->ajax_return(FLAG_OK, '', $data);

        } else {
            $cart_goods =  $model->find(array(
                'conditions'    => "rec_id ={$rec_id} AND user_id={$this->user_id}"
            ));
            if (!$cart_goods) {
                $this->ajax_return(FLAG_ERROR, '购物车没有该商品');
            }
            //从购物车中删除
            $droped_rows = $model->drop("rec_id= {$rec_id} AND user_id= {$this->user_id}", 'store_id');

            if (!$droped_rows) {
                $this->ajax_return(FLAG_ERROR, '删除购物车商品失败！');
            }
            //返回结果
            $dropped_data = $model->getDroppedData();//获取时时保存的已删除记录
            $cart_status = $this->get_cart_status();
            $this->ajax_return(FLAG_OK, '操作成功！', $cart_status);
        }

    }

    /**
     * 全选或取消全部商品
     * @author jyx
     * @date 2015/11/09
     */
    public function checkedAll() {
        $action = '全选或取消全部商品';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        if (!$user_id = $this->checkLogin()) {
            $this->ajax_return(ERROR_LOGIN, '请您登陆！');
        }
        $checked = $this->get_gp('checked', 'P');
        $checked = $checked == 1 ? 1 : 0;
        $model = m('cart');
        $sql = "UPDATE ".DB_PREFIX."cart SET checked={$checked} WHERE user_id={$user_id}";
        $flag = $model->query($sql);
        if ($flag === false) {
            $this->ajax_return(FLAG_ERROR, '更新信息失败！');
        }
        //获取购物车中的信息
        $data = $this->_getCartInfo($user_id, $model);
        $this->ajax_return(FLAG_OK, '', $data);
    }

    /**
     * 商铺的全选或取消
     * @author jyx
     * @date 2015/11/09
     */
    public function checkedStore() {
        $action = '商铺的全选或取消';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        $checked = $this->get_gp('checked', 'P');//是否选中,1:选中,0:未选中
        $store_id = $this->get_gp('store_id', 'P');//商铺的id
        $checked = ($checked == 1) ? 1 : 0;
        $store_id = $store_id ? intval($store_id) : 0;
        if (!$store_id) {
            $this->ajax_return(FLAG_ERROR, '商铺的id不正确！');
        }
        if (!$user_id = $this->checkLogin()) {
            $this->ajax_return(ERROR_LOGIN, '请您登陆！');
        }
        $model = m('cart');
        $sql = "UPDATE ".DB_PREFIX."cart SET checked={$checked} WHERE store_id={$store_id} AND user_id={$user_id}";
        $flag = $model->query($sql);
        if ($flag === false) {
            $this->ajax_return(FLAG_ERROR, '更新信息失败！');
        }
        //获取购物车中的信息
        $data = $this->_getCartInfo($user_id, $model);
        $this->ajax_return(FLAG_OK, '', $data);
    }

    /**
     * 单个商品的选中或取消
     * @author jyx
     * @date 2015/11/09
     */
    public function checkedGoods() {
        $action = '单个商品的选中或取消';
        setLogParameter($action);
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        if (!$user_id = $this->checkLogin()) {
            $this->ajax_return(ERROR_LOGIN, '请您登陆！');
        }
        $rec_id = $this->get_gp('rec_id', 'P');//购物车的自增id
        $checked = $this->get_gp('checked', 'P');//是否选中,1:选中,0:未选中
        $checked = ($checked == 1) ? 1 : 0;
        $rec_id = $rec_id ? intval($rec_id) : 0;
        if (!$rec_id) {
            $this->ajax_return(FLAG_ERROR, '购物车的id不正确！');
        }
        $model = m('cart');
        $sql = "UPDATE ".DB_PREFIX."cart SET checked={$checked} WHERE rec_id={$rec_id} AND user_id={$user_id}";
        $flag = $model->query($sql);
        if ($flag === false) {
            $this->ajax_return(FLAG_ERROR, '更新信息失败！');
        }
        //获取购物车中的信息
        $data = $this->_getCartInfo($user_id, $model);
        $this->ajax_return(FLAG_OK, '', $data);
    }


    /**
     * 获取购物车状态
     * @author Garbin
     * @return array
     */
    private function get_cart_status()
    {
        /* 默认的返回格式 */
        $data = array(
            'status'    =>  array(
                'quantity'  =>  0,      //总数量
                'amount'    =>  0,      //总金额
                'kinds'     =>  0,      //总种类
            ),
            'carts'     =>  array(),    //购物车列表，包含每个购物车的状态
        );

        /* 获取所有购物车 */
        $carts = $this->get_carts();
        if (empty($carts))
        {
            return $data;
        }
        $data['carts']  =   $carts;
        foreach ($carts as $store_id => $cart)
        {
            $data['status']['quantity'] += $cart['quantity'];
            $data['status']['amount']   += $cart['amount'];
            $data['status']['kinds']    += $cart['kinds'];
        }

        return $data;
    }

    /**
     * 以购物车为单位获取购物车列表及商品项
     * @author    Garbin
     * @return    void
     */
    private function get_carts($store_id = 0)
    {
        $carts = array();

        /* 获取所有购物车中的内容 */
        $where_store_id = $store_id ? ' AND cart.store_id=' . $store_id : '';

        /* 只有是自己购物车的项目才能购买 */
        $where_user_id = $this->user_id ? " AND cart.user_id=" . $this->user_id : '';
        $cart_model =& m('cart');
        $cart_items = $cart_model->find(array(
            'conditions'    => 'session_id = \'' . SESS_ID . "'" . $where_store_id . $where_user_id,
            'fields'        => 'this.*,store.store_name',
            'join'          => 'belongs_to_store',
        ));
        if (!$cart_items) {
            return $carts;
        }
        $kinds = array();
        foreach ($cart_items as $item)
        {
            /* 小计 */
            $item['subtotal']   = $item['price'] * $item['quantity'];
            $kinds[$item['store_id']][$item['goods_id']] = 1;

            /* 以店铺ID为索引 */
            empty($item['goods_image']) && $item['goods_image'] = Conf::get('default_goods_image');
            $carts[$item['store_id']]['store_name'] = $item['store_name'];
            $carts[$item['store_id']]['amount']     += $item['subtotal'];   //各店铺的总金额
            $carts[$item['store_id']]['quantity']   += $item['quantity'];   //各店铺的总数量
            $carts[$item['store_id']]['goods'][]    = $item;
        }

        foreach ($carts as $_store_id => $cart)
        {
            $carts[$_store_id]['kinds'] =   count(array_keys($kinds[$_store_id]));  //各店铺的商品种类数
        }

        return $carts;
    }


}